﻿using JuCloudy.Framework.Interface;
using JuCloudy.Platform.Structure.UserControls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Reflection;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;

namespace JuCloudy.Platform.Structure
{
    public partial class MainPage : UserControl, JuCloudy.Framework.Interface.IStructure
    {
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += (obj, e) =>
            {
                this.Layer_App.Children.Clear();
                this.Layer_App.Children.Add(splash);
                this.Layer_App.Visibility = Visibility.Visible;

                JuCloudy.Framework.Storge.VariableHelper.Init();
                InitWebServiceHost();                
            };
        }

        private UserControls.Splash splash = new UserControls.Splash();

        private UserControls.jLoadingWindow jLoadingWindow = new UserControls.jLoadingWindow();

        public void InitializeXap(Uri uri,String AssemlyName,String MainPageName,Grid ui)
        {
            this.InitializeXap(uri, AssemlyName, MainPageName, ui, null);
        }

        public void InitializeXap(Uri uri, string AssemlyName, string MainPageName, Grid ui, EventHandler OnCompleted)
        {
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += ((obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;
                JuCloudy.Framework.Storge.Session.Client["app_" + AssemlyName] = e.Result;

                Assembly mainAssembly = XPackage.LoadAssembly(AssemlyName);
                UIElement mainFrame = new UserControl();
                try
                {
                    mainFrame = mainAssembly.CreateInstance(String.Format("{0}.{1}", AssemlyName, MainPageName)) as UIElement;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                if (mainFrame is IModule)
                {
                    try
                    {
                        ((IModule)mainFrame).InitResource();
                        this.CloseLoading();
                        ui.Children.Clear();
                        ui.Children.Add(mainFrame);
                        ui.Visibility = Visibility.Visible;
                        if (OnCompleted != null)
                            OnCompleted.Invoke(this, new EventArgs());
                    }
                    catch (Exception ex) { this.CloseLoading(); throw ex; }
                }
                else if (mainFrame is ISkin)
                {
                    try
                    {
                        ((ISkin)mainFrame).InitResources(OnCompleted);
                        this.CloseLoading();
                        ui.Children.Clear();
                        ui.Children.Add(mainFrame);
                        ui.Visibility = Visibility.Visible;
                    }
                    catch (Exception ex) { this.CloseLoading(); throw ex; }
                }
                else
                {
                    this.CloseLoading();
                    ui.Children.Clear();
                    ui.Children.Add(mainFrame);
                    ui.Visibility = Visibility.Visible;
                    if (OnCompleted != null)
                        OnCompleted.Invoke(this, new EventArgs());
                }
            });
            webClient.OpenReadAsync(uri);//获取另一个xap文件
        }
        
        public Uri CompleteUri(string url)
        {
            return new Uri(HtmlPage.Document.DocumentUri, url);
        }

        public void ShowChildDialog(UIElement ui, String header)
        {
            this.Layer_Popup.Children.Clear();
            this.Layer_Popup.Children.Add(
                jChildWindow.Show(ui, header));
            this.Layer_Popup.Visibility = Visibility.Visible;
        }

        public void ShowChildDialog(UIElement ui,String header, double Width, double Height)
        {
            this.Layer_Popup.Children.Clear();
            var win = jChildWindow.Show(ui, header);
            win.Height = Height;
            win.Width = Width;
            this.Layer_Popup.Children.Add(win);
            this.Layer_Popup.Visibility = Visibility.Visible;
        }

        public void CloseChildDialog()
        {
            this.Layer_Popup.Children.Clear();
            this.Layer_Popup.Visibility = Visibility.Collapsed;
        }

        public void ShowLoading()
        {
            //jLoadingWindow.Show();
            this.IsEnabled = false;
            this.Layer_Loading.Visibility = Visibility.Visible;
        }

        public void ShowMessage(string Title, string Content, Data.Entity.MessageType MsgType)
        {
            TextBlock txtcontent = new TextBlock();
            txtcontent.Text = Content;
            txtcontent.FontSize = 14;
            this.Layer_Popup.Children.Clear();
            this.Layer_Popup.Children.Add(
                jMessageBox.Show(txtcontent,Title,MsgType));
            this.Layer_Popup.Visibility = Visibility.Visible;
        }

        public void CloseLoading()
        {
            //jLoadingWindow.Close();
            this.IsEnabled = true ;
            this.Layer_Loading.Visibility = Visibility.Collapsed ;
        }

        public void InitializeXap(Data.Entity.SysAppInfo AppInfo, Data.Entity.SysAppModule AppModule,Grid ui)
        {
            InitializeXap(CompleteUri("/ClientBin/"+AppModule.Filename),
                    AppInfo.AppAssembly, AppInfo.AppMainPageName, ui);
        }
        
        public void InitSystemVariable()
        {
            splash.SetText("载入系统设置...");
            SystemVariable.SystemVariableSoapClient client = new SystemVariable.SystemVariableSoapClient();
            client.GetEntitiesCompleted += (obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;

                var entities = e.Result.Deserialize(typeof(List<JuCloudy.Data.Entity.SysVariable>)) 
                    as List<JuCloudy.Data.Entity.SysVariable>;
                foreach (var entity in entities)
                {
                    if(entity.Value!=null)
                        JuCloudy.Framework.Storge.Session.Client[entity.Name] = entity.Value;
                    else
                        JuCloudy.Framework.Storge.Session.Client[entity.Name] = entity.DeafultValue;
                }
                //载入客户端IP地址
                InitIPAddress();
            };
            client.GetEntitiesAsync();
        }

        public void InitIPAddress()
        {
            splash.SetText("载入本地参数...");
            IPAddressService.IPAddressServiceClient client = new IPAddressService.IPAddressServiceClient();
            client.DoWorkCompleted += (obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;
                else
                {
                    JuCloudy.Framework.Storge.Session.Client["IPADDRESS"] = e.Result;                   
                }
                //加载界面数据
                InitStruCateAppi();  
                  
            }; 
            client.DoWorkAsync();
        }

        public void InitWebServiceHost()
        {
            splash.SetText("载入服务参数...");
            SystemService.WSSysServiceSoapClient client = new SystemService.WSSysServiceSoapClient();
            client.WebServiceHostCompleted += (obj, e) =>
            {
                if (e.Error != null)
                    throw e.Error;
                else
                {
                    JuCloudy.Framework.Storge.Session.Client["WEBSERVICEHOST"] = e.Result;
                    InitSystemVariable();
                }                
            };
            client.WebServiceHostAsync();
        }

        public void InitStruCateAppi()
        {
            splash.SetText("加载主界面...");
            //启动界面
            InitializeXap(CompleteUri("/ClientBin/JuCloudy.Platform.Structure.UI.xap"),
                "JuCloudy.Platform.Structure.UI", "MainPage", this.Layer_App, (objx, e) =>
                {
                    this.Layer_High.Visibility = Visibility.Collapsed;
                });
        }

        public void InitializeXap(int AppId, Grid ui, TextBlock AppName, TextBlock AppIntro)
        {
            ShowLoading();
            SystemService.WSSysServiceSoapClient client =
                           new SystemService.WSSysServiceSoapClient();
            client.GetAppInfoEntityAsync(AppId);
            client.GetAppInfoEntityCompleted += (obj, ex) =>
            {
                if (ex.Error != null)
                    throw ex.Error;
                var AppInfo = ex.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppInfo))
                    as JuCloudy.Data.Entity.SysAppInfo;
                client.GetNewestAppModuleEntityAsync(AppId);
                client.GetNewestAppModuleEntityCompleted += (objn, exn) =>
                {
                    CloseLoading();
                    if (exn.Error != null)
                        throw exn.Error;

                    var appmodule = exn.Result.Deserialize(typeof(JuCloudy.Data.Entity.SysAppModule))
                        as JuCloudy.Data.Entity.SysAppModule;
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        AppName.Text = AppInfo.AppName;
                        AppIntro.Text = AppInfo.AppIntroduction;
                    });
                    this.InitializeXap(AppInfo, appmodule, ui);
                };
            };
        }

        public void ShowCustomRoot(Data.Entity.SysAppInfo AppInfo, Data.Entity.SysAppModule AppModule)
        {
            this.InitializeXap(AppInfo, AppModule, this.Layer_Custom);
        }

        public void HideCustomRoot()
        {
            this.Layer_Custom.Children.Clear();
            this.Layer_Custom.Visibility = Visibility.Collapsed;
            this.Layer_High.Visibility = Visibility.Visible;
        }
    }
}
